package com.xinyan.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xinyan.exception.*;
import com.xinyan.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        log.info("=======出现异常:{}========",JSON.toJSONString(e));
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(value = ServiceException.class)
    public R handleServiceException(ServiceException e) {
        int code = 0;
        if (e instanceof InsertException) {
            code = 9001;
        } else if (e instanceof UsernameDuplicatedException) {
            code = 9002;
        } else if (e instanceof PasswordNotMatchException) {
            code = 9003;
        } else if (e instanceof UserNotFoundException) {
            code = 9004;
        } else if (e instanceof UserNotLoginException) {
            code = 9005;
        }
        return R.fail(code, e.getMessage());
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public R handle(ConstraintViolationException e){
        log.info("===============");
        log.info(JSON.toJSONString(e, SerializerFeature.IgnoreErrorGetter));
        log.info("===============");
        return R.fail("参数校验异常：" +e.getMessage());
    }
}
